package com.Java.train.gateway.filters;

import cn.hutool.json.JSONObject;
import com.Java.train.gateway.utils.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class LoginMemberFilter implements GlobalFilter, Ordered {
    private static final Logger LOG = LoggerFactory.getLogger(LoginMemberFilter.class);
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1.获取path
        String path = exchange.getRequest().getURI().getPath();

        // 2.排除不需要的路径
        if(path.contains("/admin")
                || path.contains("/member/send-code")
                || path.contains("/member/login")
                || path.contains("/business/hello")
                || path.contains("/batch/hello")
                || path.contains("/admin/**")
                || path.contains("/member/hello")
                || path.contains("/business/kaptcha")){
            LOG.info("不需要登录验证:{}" + path);
            return chain.filter(exchange); // 继续下一个拦截器
        } else {
            LOG.info("需要登录验证:{}", path);
        }
        // 3.获取前端登录验证
        String token = exchange.getRequest().getHeaders().getFirst("token");
        LOG.info("会员认证开始token为:{}", token);
        if(token == null || token.isEmpty()){
            LOG.info("token为空，请求被拦截");
            // 设置返回报错参数
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return  exchange.getResponse().setComplete(); // 设置完成请求（有问题返回）
        } else {
            LOG.info("token:{}", token);
        }

        // 检查token是否正确，是否被修改过，是否过期
        boolean validate = JwtUtil.validate(token);
        if(validate){
            LOG.info("token有效，通过验证");
            return chain.filter(exchange);
        } else {
            LOG.warn("token无效，请求被拦截");
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
    }

    /**
      * @Description: 设置优先级
      * @param
      * @return int数越小优先级越高
      */
    @Override
    public int getOrder() {
        return 0;
    }
}
